﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Rotempco.Core.Logic
{
    public static class ListLogic
    {
        public static List<TObject> SortLinkedList<TObject>(List<TObject> linkedList, string primaryKeyName, string foreignKeyName)
        {
            PropertyInfo primaryKeyPropertyInfo = typeof(TObject).GetProperty(primaryKeyName);
            PropertyInfo foreignKeyPropertyInfo = typeof(TObject).GetProperty(foreignKeyName);

            List<TObject> sortedList = new List<TObject>();
            int numberOfItterations = linkedList.Count;
            while (linkedList.Count > 0)
            {
                if (numberOfItterations-- < 0)
                    throw new Exception("Broken list");

                TObject workItem = linkedList[0];

                while (1 == 1)
                {
                    object foreignKeyValue = foreignKeyPropertyInfo.GetValue(workItem, null);
                    if (foreignKeyValue == null)
                        break;

                    long foreignValue = (long)foreignKeyValue;
                    TObject predecessor = linkedList.Where(f => (long)(primaryKeyPropertyInfo.GetValue(f, null)) == foreignValue).FirstOrDefault();

                    if (predecessor == null)
                        break;

                    workItem = predecessor;
                }

                linkedList.Remove(workItem);

                sortedList.Add(workItem);
            }

            return sortedList;

        }
    }
}
